﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace Anno.Util
{
    public class Bash
	{
#if NETSTANDARD || NET461
	/// <summary>
	/// 
	/// </summary>
	private static bool _linux { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

		/// <summary>
		/// 
		/// </summary>
		private static bool _mac { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
		/// <summary>
		/// 
		/// </summary>
		private static bool _windows { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#else
		/// <summary>
		/// 
		/// </summary>
		private static bool _linux { get; } = Environment.OSVersion.Platform.ToString() == "Unix";

		/// <summary>
		/// 
		/// </summary>
		private static bool _mac { get; } = Environment.OSVersion.Platform.ToString() == "MacOSX";
		/// <summary>
		/// 
		/// </summary>
		private static bool _windows { get; } = !(Bash._linux || Bash._mac);
#endif
		/// <summary>
		/// 
		/// </summary>
		internal static string _bashPath { get; }

		/// <summary>
		/// 
		/// </summary>
		public static bool Native { get; } = (Bash._linux || Bash._mac) ? true : false;

		/// <summary>
		/// 
		/// </summary>
		static Bash()
		{
			Bash._bashPath = (Bash.Native ? "/bin/bash" : "cmd.exe");
			if (!File.Exists(Bash._bashPath) && Bash.Native)
			{
				if (File.Exists("bin/sh"))
				{
					Bash._bashPath = "bin/sh";
					return;
				}
				if (File.Exists("/usr/bin/sh"))
				{
					Bash._bashPath = "/usr/bin/sh";
					return;
				}
				if (File.Exists("/usr/bin/bash"))
				{
					Bash._bashPath = "/usr/bin/bash";
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public static string CurrentExePath
		{
			get
			{
				string fileName = Process.GetCurrentProcess().MainModule.FileName;
				return fileName.Substring(0, fileName.LastIndexOf("/"));
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public static Linux Linux
		{
			get
			{
				return new Linux();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public static Windows Windows
		{
			get
			{
				return new Windows();
			}
		}
	}
}
